#include "Mesh.h"

using namespace tri;

// ------------------------------------------------------------------------------------------------
Mesh::Mesh()
{}

// ------------------------------------------------------------------------------------------------
Mesh::Mesh( const std::vector<Math::dvec3> &vertices, const std::vector<unsigned int> &indices )
{
	for( size_t i = 0; i<vertices.size(); ++i )
	{
		Vertex v;
		v.position = vertices[i];
		v.normal   = Math::vec3(0.f);

		_vtx.push_back( v );
	}

	for( size_t i = 0; i<_vtx.size()-3; i+=3 )
	{
		const Math::dvec3 v0 = _vtx[i+0].position;
		const Math::dvec3 v1 = _vtx[i+1].position;
		const Math::dvec3 v2 = _vtx[i+2].position;
		const Math::vec3 n   = Math::vec3(Math::cross( v1-v0, v2-v0 ));

		Face f( i+0, i+1, i+2 );
		f.normal = n;

		_faces.push_back( f );
	}
}

// ------------------------------------------------------------------------------------------------
Mesh::~Mesh()
{}

// ------------------------------------------------------------------------------------------------
void Mesh::updateBoundingBox()
{
	for( size_t i=0; i<_vtx.size(); ++i )
		_boundingBox.extend(_vtx[i].position);
}

// ------------------------------------------------------------------------------------------------
void Mesh::computeNormals()
{
	for( size_t i = 0; i<_vtx.size(); ++i )
	{
		Math::vec3 n;

		for( size_t j=0; j<_faces.size(); ++j )
		{
			if( _faces[j].v0 == i ) n+= _faces[j].normal;
			if( _faces[j].v1 == i ) n+= _faces[j].normal;
			if( _faces[j].v2 == i ) n+= _faces[j].normal;
		}

		_vtx[i].normal = Math::normalize( n+Math::vec3(1e-9) );
	}
}